package com.cunshe.web;

import com.cunshe.domain.*;
import com.cunshe.service.*;
import com.sunkee.commons.utils.DateUtils;
import com.sunkee.commons.utils.ListUtils;
import com.sunkee.commons.utils.StringUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/")
public class HomeController {

    @Autowired
    private BannerService bannerService;
    @Autowired
    private CooperativeCustomersService cooperativeCustomersService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private CompanyProfileService companyProfileService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private DataDownService dataDownService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductImageService productImageService;

    @ModelAttribute
    public void loadMenu(Model model){
        List<Menu> menus = menuService.all();
        menus = (List<Menu>) ListUtils.list2Tree(menus);

        CompanyProfile companyProfile = companyProfileService.get();

        int i = DateUtils.differentDays(companyProfile.getEstablishDate(), new Date());
        int year = 1;
        if(i > 1){
            year = i / 365;
        }
        model.addAttribute("companyProfile", companyProfile);
        model.addAttribute("year", year);
        model.addAttribute("page", "");
        model.addAttribute("menus", menus);
    }

    /** 首页 */
    @GetMapping("")
    public String index(HttpServletRequest request, Model model){
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("user-agent"));
        String name = userAgent.getOperatingSystem().getDeviceType().getName();
        List<Banner> banners = bannerService.list(Banner.builder().build());
        Banner banner4 = null, banner5 = null;
        for (Banner banner : banners) {
            if(!"Computer".equals(name)){
                banner.setUrl(banner.getMobileUrl());
            }
            if(StringUtils.isNotBlank(banner.getDescription())){
                banner.setDescription(banner.getDescription().replaceAll("∮", "<br/>"));
            }
            if(banner.getId() == 4){
                banner4 = banner;
            }
            if(banner.getId() == 5){
                banner5 = banner;
            }
        }

        List<CooperativeCustomers> coperativeCustomers = cooperativeCustomersService.all();

        List<News> news = newsService.top(3);

        model.addAttribute("banners", banners);
        model.addAttribute("banner4", banner4);
        model.addAttribute("banner5", banner5);
        model.addAttribute("coperativeCustomers", coperativeCustomers);
        model.addAttribute("news", news);
        model.addAttribute("page", "home");
        return "index";
    }

    /** 公司简介 */
    @GetMapping(value = "companyProfile")
    public String companyProfile(){

        return "company";
    }

    /** 合作客户 */
    @GetMapping(value = "cooperativeCustomers")
    public String cooperativeCustomers(Model model){
        List<CooperativeCustomers> all = cooperativeCustomersService.all();

        model.addAttribute("coperativeCustomers", all);
        return "teamwork";
    }

    /** 产品 */
    @GetMapping(value = "products")
    public String products(Model model){
        List<Product> list = productService.list(Product.builder().build());
        List<Menu> menus = menuService.all();
        for (Product product : list) {
            String category1 = menus.stream().filter(var -> String.valueOf(var.getId()).equals(product.getCategory1())).findFirst()
                    .map(Menu::getTitle)
                    .orElse("");
            product.setCategory1Name(category1);

            String category2 = menus.stream().filter(var -> String.valueOf(var.getId()).equals(product.getCategory2())).findFirst()
                    .map(Menu::getTitle)
                    .orElse("");
            product.setCategory2Name(category2);
        }

        List<String> seriesList = null;
        if(!CollectionUtils.isEmpty(list)){
            seriesList = list.stream()
                    .map(Product::getCategory1Name)
                    .distinct()
                    .collect(Collectors.toList());
        }

        model.addAttribute("seriesList", seriesList);
        model.addAttribute("products", list);
        return "products";
    }

    /** 产品列表 */
    @GetMapping(value = "product_list")
    public String product_list(String s, Model model) {
        if(s != null){
            s = s.trim();
        }

        List<Menu> menus = menuService.all();
        List<Product> productList = productService.list(Product.builder().category2(s).build());
        for (Product product : productList) {
            String category1 = menus.stream().filter(var -> String.valueOf(var.getId()).equals(product.getCategory1())).findFirst()
                    .map(Menu::getTitle)
                    .orElse("");
            product.setCategory1Name(category1);

            String category2 = menus.stream().filter(var -> String.valueOf(var.getId()).equals(product.getCategory2())).findFirst()
                    .map(Menu::getTitle)
                    .orElse("");
            product.setCategory2Name(category2);
        }

        model.addAttribute("productList", productList);
        return "product-list";
    }

    /** 产品详情 */
    @GetMapping(value = "product_detail_{id}")
    public String product_detail(@PathVariable(value = "id") Long id, Model model){
        Product product = productService.get(id);

        if(product == null){
            return null;
        }
        List<ProductImage> productImage = productImageService.getProductImage(id);
        String mainImage = "";
        if(!CollectionUtils.isEmpty(productImage)) {
            mainImage = productImage.get(0).getUrl();
        }
        List<Product> related = productService.list(Product.builder().category1(product.getCategory1()).build());

        model.addAttribute("product", product);
        model.addAttribute("productImage", productImage);
        model.addAttribute("mainImage", mainImage);
        model.addAttribute("related", related);
        return "product-detail";
    }

    /** 服务支持 */
    @GetMapping(value = "service")
    public String service(Model model){

        return "service";
    }

    /** 资料下载 */
    @GetMapping(value = "download")
    public String download(String s, Model model){
        List<DataDown> dataDowns = dataDownService.all();

        List<String> seriesList = null;
        if(!CollectionUtils.isEmpty(dataDowns)){
            seriesList = dataDowns.stream()
                    .map(DataDown::getSeries)
                    .distinct()
                    .collect(Collectors.toList());

            String seriesName = StringUtils.isNotBlank(s) ? s : seriesList.get(0);

            dataDowns = dataDowns.stream()
                    .filter(var -> var.getSeries().equals(seriesName))
                    .collect(Collectors.toList());
        }

        model.addAttribute("seriesList", seriesList);
        model.addAttribute("dataDowns", dataDowns);
        return "download";
    }

    /** 新闻 */
    @GetMapping(value = {"news", "news_{type}"})
    public String news(@PathVariable(value = "type", required = false) Integer type, Model model){
        List<News> news = newsService.list(News.builder().type(type).build());

        model.addAttribute("type", type);
        model.addAttribute("news", news);
        return "new-list";
    }

    /** 新闻详情 */
    @GetMapping(value = "news_detail_{id}")
    public String news_detail(@PathVariable(value = "id") Long id, Model model){
        News news = newsService.get(id);

        model.addAttribute("news", news);
        return "news-detail";
    }

    /** 联系我们 */
    @GetMapping(value = "contact_us")
    public String contact_us(Model model){

        return "contact-us";
    }




}
